#include <devicemanager.h>

DeviceManager::DeviceManager(QString devicePath, int deviceId)
{
	this->devicePath = devicePath;
	timer = new QTimer(this);
	timer->setSingleShot(true);
	id = deviceId;
	QObject::connect(timer, SIGNAL(timeout()), this, SLOT(move()));
}

DeviceManager::~DeviceManager()
{
	stop();
	finished();
}

/**
 * Setup a pattern for playing.
 */
void DeviceManager::setPattern(QList<int> pattern)
{
	this->pattern = pattern;
}

/**
 * Start playing the pattern.
 */
void DeviceManager::run()
{
	index = 0;
	move();
}

/**
 * Stop playing the pattern.
 */
void DeviceManager::stop()
{
	timer->stop();
	vibrate(0);
}

/**
 * Vibrate the device and setup the timer for the next run.
 * If the index of the pattern is at the end, emit terminateSignal
 * and stop the device.
 */
void DeviceManager::move()
{
	if ((index+1) < pattern.size()) {
		//qDebug() << devicePath;
		vibrate(pattern.at(index++));
		//qDebug() << "duration ..." << pattern.at(index);
		timer->start(pattern.at(index++));	
	} else {		
		emit terminateSignal();
		stop();
	}
}

/**
 * Vibrate the device.
 */
void DeviceManager::vibrate(int strength)
{
	//qDebug() << "Vibrating ..." << strength;
	QFile device(devicePath + "/brightness");
	device.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate);
	QTextStream output(&device);
	output << strength;
	device.close();
	bool pos;
	if (strength > 0) {
		pos = true;
	} else {
		pos = false;
	}
	emit vibrationSignal(pos, id);
}


